package org.acghub.config.reader;


import com.opencsv.CSVReader;
import org.acghub.config.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/24/星期四 11:24
 * @Version 1.0
 */
public class CsvTableReader implements TableReader {
    @Override
    public TableMeta readMeta(File file) {
        try (CSVReader reader = newCSVReader(file)) {
            return readMeta(reader);
        } catch (Exception e) {
            throw new TableReadException("readMeta 读取文件失败", e);
        }
    }

    @Override
    public TableData readData(File file) {
        try (CSVReader reader = newCSVReader(file)) {
            return readData(reader);
        } catch (Exception e) {
            throw new TableReadException("readData 读取文件失败", e);
        }
    }

    private CSVReader newCSVReader(File file) throws Exception {
        return new CSVReader(new InputStreamReader(new FileInputStream(file), Charset.forName("GBK")));
    }

    private TableMeta readMeta(CSVReader reader) throws Exception {
        String[] meteCommentRow = reader.readNext();
        String[] metaRow = reader.readNext();
        return new TableMeta(StringUtils.trim(metaRow[0]), StringUtils.trim(metaRow[2]), readHeader(reader));
    }

    private TableHeader readHeader(CSVReader reader) throws Exception {
        String[] commentRow = reader.readNext();
        String[] nameRow = reader.readNext();
        String[] typeRow = reader.readNext();
        String[] exportRow = reader.readNext();
        String[] delimitersRow = reader.readNext();
        final int columnCount = commentRow.length;
        final TableHeader tableHeader = new TableHeader(0, columnCount);
        for (int i = 0; i < columnCount; i++) {
            if (!StringUtils.contains(exportRow[i], "s")) {
                continue;
            }
            tableHeader.add(new TableField(i, StringUtils.trim(commentRow[i]), StringUtils.trim(nameRow[i]), StringUtils.trim(typeRow[i]), StringUtils.trim(delimitersRow[i])));
        }
        return tableHeader;
    }

    private TableData readData(CSVReader reader) throws Exception {
        TableData tableData = new TableData(readMeta(reader));
        // skip data blank row
        reader.readNext();
        String[] dataRow;
        while ((dataRow = reader.readNext()) != null) {
            TableDataRow tableDataRow = new TableDataRow((int) reader.getRecordsRead());
            for (int i = 0; i < dataRow.length; i++) {
                if (!tableData.getMeta().hasColumnIndex(i)) {
                    continue;
                }
                TableDataCell cell = new TableDataCell(i, dataRow[i]);
                tableDataRow.add(cell);
            }
            tableData.add(tableDataRow);
        }
        return tableData;
    }
}
